//服务器文件：处理网络数据的文件
#pragma once

#include "Protocol.hpp"

#include <iostream>
#include <string>

enum
{   
    Div_Zero = 1,//除0
    Mod_Zero,    //模0
    Other_Oper   //不认识操作符
};

class ServerCalc
{
public:
    ServerCalc()
    {}
    ~ServerCalc()
    {}
public:
    //解析收到的Request报文和构建Response报文
    std::string Handler(std::string &c_req_package)  //"len\n_x + _y"
    {
        //解析Request报文
        std::string c_req_content;   
        bool ret = Decode(c_req_package, &c_req_content);
        //std::cout << "1" << std::endl;
        if(!ret) return "none";
        Request req;
        ret = req.Deserialize(c_req_content);
        //std::cout << "2" << std::endl;
        if(!ret) return "none";

        //处理数据
        Response resp = CalculatorHelper(req);

        //构建Response报文
        std::string s_rsp_content;
        ret = resp.Serialize(&s_rsp_content);
        //std::cout << "3" << std::endl;
        if(!ret) return "none";
        std::string s_rsp_package = Encode(s_rsp_content);
        return s_rsp_package;
    }
    //计算器实现函数
    Response CalculatorHelper(Request &req)
    {
        Response resp(0, 0);
        switch(req._op)
        {
            case '+':
                resp._result = req._x + req._y;
                break;
            case '-':
                resp._result = req._x - req._y;
                break;
            case '*':
                resp._result = req._x * req._y;
                break;
            case '/':
                if(req._y == 0) resp._code = Div_Zero;
                else resp._result = req._x / req._y;
                break;
            case '%':
                if(req._y == 0) resp._code = Mod_Zero; 
                else resp._result = req._x % req._y;
                break;
            default:
                resp._code = Other_Oper;
                break;
        }
        return resp;
    }
};